package file;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class MD5Calculator {

	public static byte[] createChecksum(String filename) throws Exception {
		InputStream fis = new FileInputStream(filename);

		byte[] buffer = new byte[1024];
		MessageDigest complete = MessageDigest.getInstance("MD5");
		int numRead;

		do {
			numRead = fis.read(buffer);
			if (numRead > 0) {
				complete.update(buffer, 0, numRead);
			}
		} while (numRead != -1);

		fis.close();
		return complete.digest();
	}

	public static String getMD5Checksum(String filename) throws Exception {
		byte[] b = createChecksum(filename);
		StringBuilder result = new StringBuilder();

		for (int i = 0; i < b.length; i++) {
			result.append(Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1));
		}

		return result.toString();
	}

	public static void main(String args[]) {
		try {
			File file = new File("/home/gmarcone/Ubuntu12.04 PIS/Ubuntu12.04 PIS.vmdk");

			if (file.isDirectory()) {
				for (File subFiles : file.listFiles() ) {
					System.out.println(subFiles.getName() + "\t\t" + getMD5Checksum(subFiles.getAbsolutePath()));
				}
			} else if (file.isFile()) {
				System.out.println(file.getName() + "\t\t" + getMD5Checksum(file.getAbsolutePath()));
			} else {
				System.out.println("What is this?" + file.getAbsolutePath());
			}

		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}
}
